/**
 * 版权所有(C) COVISINT 2015-2025
 * Copyright 2015-2025 COVISINT
 * 创建日期：Jun 29, 20172:29:30 PM
 * 创建人：yyang
 */
package com.wechat.framework.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.covisint.platform.GsonUtils.GsonUtils;
import com.covisint.platform.httpclient.utils.HttpClientUtils;
import com.google.gson.reflect.TypeToken;
import com.wechat.framework.constants.WechatCodeInfoConstant;
import com.wechat.framework.messages.files.ErrorMsg;
import com.wechat.framework.messages.oauth.OAuthUser;
import com.wechat.framework.messages.token.AccessToken;

public class WechatFilesUtils {
	
	private Logger logger = LoggerFactory.getLogger(WechatFilesUtils.class);
	
	static AbstractApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/applicationContext.xml"});
	static HttpClientUtils httpClientUtils = (HttpClientUtils) context.getBean("HttpClientUtils");
	
	//@Resource
	//public static HttpClientUtils httpClientUtils;
	
	public static AccessToken getAccessToken(String corpID, String secret) {
		
		AccessToken accessToken = null;  
		  
	    String requestUrl = WechatURLUtils.ACCESS_TOKEN_URL.replace("CorpID", corpID).replace("SECRET", secret);
	    
	    try {
			String jsonResult = httpClientUtils.doGet(requestUrl);
			System.out.println(jsonResult);
			
			//返回结果不为空
			if(null != jsonResult){
				accessToken = GsonUtils.convert(jsonResult, new TypeToken<AccessToken>(){});
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
	    return accessToken;
	}

	public static String findOAuth2GetUserIdByCode(String accessToken, String code, String agentId) {
		
		OAuthUser oauthUser = null;

		String requestUrl = WechatURLUtils.GET_OAUTH2_URL.replace("ACCESS_TOKEN", accessToken).replace("CODE", code).replace("AGENTID", agentId);
		
		try {
			String jsonResult = httpClientUtils.doGet(requestUrl);
			System.out.println(jsonResult);
			//返回结果不为空
			if(null != jsonResult){
				oauthUser = GsonUtils.convert(jsonResult, new TypeToken<OAuthUser>(){});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (null != oauthUser && oauthUser.getUserId() != null) {
			return oauthUser.getUserId();
		}

		return null;
	}
	
	//获取下载临时素材文件
	public InputStream DowloadFile(String accessToken, String mediaId, String fileType, String path){
		
		ErrorMsg errorMsg = null;
		String requestUrl = WechatURLUtils.GET_MSG_URL.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
		try {
			InputStream result = null;
			Map<String, Object> resultMap = httpClientUtils.doGetDownLoad(requestUrl);
			int errorCode = (int) resultMap.get("errorCode");
			if(errorCode!=0){
				//返回错误
				errorMsg = new ErrorMsg();
				errorMsg.setErrcode(errorCode);
				errorMsg.setErrmsg(resultMap.get("errorMsg").toString());
				System.out.println(errorMsg.getErrcode()+", "+errorMsg.getErrmsg());
				//若错误码为accessToke过期,则重新获取accessToken,重新下载
				if(errorCode == WechatCodeInfoConstant.access_token_expired){
					//重新获取accessToke
					AccessToken accessTokens = getAccessToken(WechatURLUtils.WECHAT_CORPID,WechatURLUtils.WECHAT_SECRET);
					accessToken = accessTokens.getToken();
					//重新下载
					DowloadFile(accessToken, mediaId, fileType, path);
				}
			}else{
				 InputStream inputStream  =(InputStream) resultMap.get("inputStream");
				 System.out.println("inputStream:"+inputStream);
				 result = inputStream;
				 System.out.println("result1:"+result);
				 byte[] data = new byte[1024];
			     int len = 0;
		         FileOutputStream fileOutputStream = null;
			     try {
			    	   String fileName = resultMap.get("fileName").toString();
			    	   if(null==fileName||"".equals(fileName)){
			    		   fileName = "get."+fileType;
			    	   }
			           fileOutputStream = new FileOutputStream(path+fileName);//"D:\\test\\"
			           while ((len = inputStream.read(data)) != -1) {
			               fileOutputStream.write(data, 0, len);
			           }
			       } catch (IOException e) {
			           e.printStackTrace();
			       } finally {
			           if (inputStream != null) {
			               try {
			                   inputStream.close();
			               } catch (IOException e) {
			                   e.printStackTrace();
			               }
			           }
	
			           if (fileOutputStream != null) {
			               try {
			                   fileOutputStream.close();
			               } catch (IOException e) {
			                   e.printStackTrace();
			               }
			           }
			       }
			}
			System.out.println("result:"+result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//上传临时素材文件
	public static void UploadFiles(String accessToken,String fileType,String path){
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
}
